var ws;
var game={
    room:0,
    room_number:globalData.roomNumber,
    room_url:0,
    score:0,
    status:0,
    time:-1,
    round:0,
    total_num:12,
    currentScore:0,
    cardDeal:0,
    can_open:0,
    is_play:!1,
    creator_id:0,
    curr_circle:0   //当前第几圈
};
var message=[
    {num:0,text:"玩游戏，请先进群"},
    {num:1,text:"群内游戏，切勿转发"},
    {num:2,text:"别磨蹭，快点打牌"},
    {num:3,text:"我出去叫人"},
    {num:4,text:"你的牌好靓哇"},
    {num:5,text:"我当年横扫澳门五条街"},
    {num:6,text:"算你牛逼"},
    {num:7,text:"别吹牛逼，有本事干到底"},
    {num:8,text:"输得裤衩都没了"},
    {num:9,text:"我给你们送温暖了"},
    {num:10,text:"谢谢老板"}
];
var wsOperation={
    JoinRoom:"JoinRoom",
    ReadyStart:"ReadyStart",
    CloseRoom:"CloseRoom",
    PrepareJoinRoom:"PrepareJoinRoom",
    AllGamerInfo:"AllGamerInfo",
    UpdateGamerInfo:"UpdateGamerInfo",
    UpdateAccountStatus:"UpdateAccountStatus",
    StartLimitTime:"StartLimitTime",
    CancelStartLimitTime:"CancelStartLimitTime",
    GameStart:"GameStart",
    NotyChooseChip:"NotyChooseChip",
    CardInfo:"CardInfo",
    PkCard:"PkCard",
    UpdateAccountScore:"UpdateAccountScore",
    OpenCard:"OpenCard",
    Win:"Win",
    Discard:"Discard",
    BroadcastVoice:"BroadcastVoice",
    RefreshRoom:"PullRoomInfo",
    ClickToLook:"ClickToLook",
    ChooseChip:"ChooseChip",
    GuestRoom:"GuestRoom",
    AllGuestInfo:"AllGuestInfo",
    UpdateGuestInfo:"UpdateGuestInfo"
};

var httpModule={
    
    getInfo:function(){
        var postData = { "account_id": userData.accountId, "room_number": globalData.roomNumber, "game_type":globalData.gameType };
        Vue.http.post("getManageInfo",postData).then(function(e){
            var t=e.body;
            if(0==t.result){
                if(0==t.data.length){
                    reconnectSocket();
                    appData.is_connect=!0;
                } else {
                    appData.activity=t.data.concat();
                    viewMethods.clickShowAlert(5,appData.activity[0].content);
                }
            } else {
                viewMethods.clickShowAlert(8, t.result_message);
            }
        },function(e){
            logMessage(e.body);
        });
    }
};
var socketModule={
    closeSocket:function(){if(ws)try{ws.close()}catch(e){console.log(e)}},
    sendData:function(e){try{if(console.log("websocket state："+ws.readyState),ws.readyState==WebSocket.CLOSED)return void reconnectSocket();ws.readyState==WebSocket.OPEN?ws.send(JSON.stringify(e)):ws.readyState==WebSocket.CONNECTING?setTimeout(function(){socketModule.sendData(e)},1e3):(console.log("websocket state："+ws.readyState),errorSocket(e.operation,JSON.stringify(e)))}catch(e){console.log(e)}},
    sendPrepareJoinRoom:function(){
        socketModule.sendData({operation:wsOperation.PrepareJoinRoom,account_id:userData.accountId,session:globalData.session,data:{room_number:globalData.roomNumber}})},

    sendJoinRoom:function(){socketModule.sendData({operation:wsOperation.JoinRoom,account_id:userData.accountId,session:globalData.session,data:{room_number:globalData.roomNumber}})},
    sendGuestRoom:function(){socketModule.sendData({operation:wsOperation.GuestRoom,account_id:userData.accountId,session:globalData.session,data:{room_number:globalData.roomNumber}})},
    sendRefreshRoom:function(){socketModule.sendData({operation:wsOperation.RefreshRoom,account_id:userData.accountId,session:globalData.session,data:{room_id:appData.game.room}})},
    sendReadyStart:function(){socketModule.sendData({operation:wsOperation.ReadyStart,account_id:userData.accountId,session:globalData.session,data:{room_id:appData.game.room}})},
    sendCloseRoom:function(){
        socketModule.sendData({
            operation: wsOperation.CloseRoom,
            account_id: userData.accountId,
            session: globalData.session,
            data: {
                room_number: globalData.roomNumber
            }
        });
    },
    sendBroadcastVoice:function(e){socketModule.sendData({operation:wsOperation.BroadcastVoice,account_id:userData.accountId,session:globalData.session,data:{room_id:appData.game.room,voice_num:e}})},
    sendClickToLook:function(){socketModule.sendData({operation:wsOperation.ClickToLook,account_id:userData.accountId,session:globalData.session,data:{room_id:appData.game.room}})},
    sendChooseChip:function(e){
        socketModule.sendData({
            operation:wsOperation.ChooseChip,
            account_id:userData.accountId,
            session:globalData.session,
            data:{room_id:appData.game.room,score:e}
        })
    },
    sendDiscard:function(){
        socketModule.sendData({
            operation:wsOperation.Discard,
            account_id:userData.accountId,
            session:globalData.session,
            data:{room_id:appData.game.room}
        })
    },
    sendOpenCard:function(){
        socketModule.sendData({
            operation:wsOperation.OpenCard,
            account_id:userData.accountId,
            session:globalData.session,
            data:{room_id:appData.game.room}
        })
    },
    sendPkCard:function(e){
        socketModule.sendData({
            operation:wsOperation.PkCard,
            account_id:userData.accountId,
            session:globalData.session,
            data:{room_id:appData.game.room,other_account_id:e}
        })
    },

    processGameRule:function(e){
        appData.ruleInfo.disable_pk=e.data.disable_pk,
        appData.ruleInfo.ticket_count=e.data.ticket_count,

        appData.ruleInfo.chip_list=e.data.chip_list,
        appData.ruleInfo.default_score=parseInt(e.data.default_score),
        appData.ruleInfo.bet_circle=e.data.bet_circle,
        appData.ruleInfo.pk_cond=e.data.pk_cond,
        appData.ruleInfo.look_cond=e.data.look_cond,
        appData.ruleInfo.xp_circle=e.data.xp_circle,
        appData.ruleInfo.xp_chip=parseInt(e.data.xp_chip);
        appData.ruleInfo.xipai_score = e.data.xipai_score;
        appData.game.creator_id = e.data.creator_id;
        for(var t=0;t<e.data.chip_list.length;t++){
            appData.scoreList1[t]=parseInt(e.data.chip_list[t]);
            appData.scoreList2[t]=e.data.chip_list[t]/2;
        }
        if(void 0!==e.data.bloody_chip_tip){
            appData.ruleInfo.bloody_chip_tip=e.data.bloody_chip_tip;
        }
    },
    processPrepareJoinRoom:function(e){
        if(4==e.data.room_status)
            return appData.roomStatus=e.data.room_status,void viewMethods.clickShowAlert(8,e.result_message);

        this.processGameRule(e);

        wxModule.config();

        if(1==e.data.is_member){
            socketModule.sendJoinRoom();
        }else{
            if(1==e.data.can_join){
                if(1==e.data.can_guest){
                    appData.joinType=1;
                    if(e.data.room_users.length>=1){
                        e.data.alert_text="房间里有"+ e.data.room_users.join("、") +"，是否加入？"
                    } else {
                        e.data.alert_text="";
                    }
                }else {
                    appData.joinType=2;
                    if(e.data.room_users.length>=1){
                        e.data.alert_text="观战人数已满，房间里有"+ e.data.room_users.join("、") +"，是否加入游戏？"
                    } else {
                        e.data.alert_text="";
                    }
                }
            }else{  //不能加入游戏
                if(1==e.data.can_guest){ 
                    appData.joinType=3;
                    if(e.data.room_users.length>=1){
                        e.data.alert_text="游戏人数已满，是否加入观战?"
                    } else {
                        e.data.alert_text="";
                    }
                } else {
                    appData.joinType=4;
                    e.data.alert_text="游戏和观战人数已满";
                }               
            }
            viewMethods.clickShowAlert(4,e.data.alert_text);
        }
    },
    processJoinRoom:function(e){
        appData.player=[],
        appData.playerBoard={
            score:[],
            round:0,
            record:""
        };
        for(var t=0;t<9;t++){
            appData.player.push({
                num:t+1,
                serial_num:t+1,
                account_id:0,
                account_status:0,
                playing_status:0,
                online_status:0,
                nickname:"",
                headimgurl:"",
                account_score:0,
                ticket_checked:0,
                is_win:!1,
                win_type:0,
                limit_time:0,
                is_operation:!1,
                win_show:!1,
                card:[],
                is_showCard:!1,
                is_pk:!1,
                is_readyPK:!1,
                card_type:0,
                messageOn:!1,
                messageText:"我们来血拼吧"
            });
            appData.playerBoard.score.push({
                account_id:0,nickname:"",
                account_score:0,
                isBigWinner:0
            });
        }

        appData.game.room=e.data.room_id;
        appData.game.currentScore=Math.ceil(e.data.benchmark);
        appData.game.score=Math.ceil(e.data.pool_score);
        appData.game.round=Math.ceil(e.data.game_num);
        appData.game.total_num=Math.ceil(e.data.total_num);
        appData.game.creator_id = Math.ceil(e.data.creator_id);
        if(audioModule.audioOn&&appData.game.currentScore==appData.ruleInfo.xp_chip){
            audioModule.stopSound("backMusic");
            audioModule.stopSound("zhangu");
            audioModule.playSound("zhangu",!0)
        }

        if(-1==e.data.limit_time){
            appData.game.time=Math.ceil(e.data.limit_time);
            viewMethods.timeCountDown();
        }

        appData.player[0].serial_num=Math.ceil(e.data.serial_num);
        for(var t=0;t<9;t++)
            if(t<=9-Math.ceil(e.data.serial_num)){
                appData.player[t].serial_num=t+Math.ceil(e.data.serial_num);
            } else {
                appData.player[t].serial_num=t+Math.ceil(e.data.serial_num)-9;
            }

        appData.player[0].account_status=Math.ceil(e.data.account_status);
        appData.player[0].account_score=Math.ceil(e.data.account_score);
        appData.player[0].nickname=userData.nickname;
        appData.player[0].headimgurl=userData.headimgurl;
        appData.player[0].account_id=userData.accountId;
        appData.player[0].card=e.data.cards.concat();
        appData.player[0].card_type=e.data.card_type;
        appData.player[0].ticket_checked=e.data.ticket_checked;
        appData.game.status=Math.ceil(e.data.room_status);

        if(2==appData.game.status){
            appData.game.cardDeal=3;
            if(4==appData.player[0].account_status){
                viewMethods.cardOver(0)
            }
        }

        appData.scoreboard=e.data.scoreboard;

        //观战功能
        appData.isWatching=0;
        setTimeout(function(){
            appData.showGuest=0
        },100);
    },
    processRefreshRoom:function(e){
        appData.player=[],
        appData.playerBoard={score:[],round:0,record:""};
        for(var t=0;t<9;t++)
            appData.player.push({
                num:t+1,
                serial_num:t+1,
                account_id:0,
                account_status:0,
                playing_status:0,
                online_status:0,
                nickname:"",
                headimgurl:"",
                account_score:0,
                ticket_checked:0,
                is_win:!1,
                win_type:0,
                limit_time:0,
                is_operation:!1,
                win_show:!1,
                card:[],
                is_showCard:!1,
                is_pk:!1,
                is_readyPK:!1,
                card_type:0,
                messageOn:!1,
                messageText:"我们来血拼吧"
            }),
            appData.playerBoard.score.push({
                account_id:0,
                nickname:"",
                account_score:0,
                isBigWinner:0
            });
        for(var t=0;t<appData.player.length;t++)
            t<=appData.player.length-Math.ceil(e.data.serial_num)?
            appData.player[t].serial_num=t+Math.ceil(e.data.serial_num):
            appData.player[t].serial_num=t+Math.ceil(e.data.serial_num)-appData.player.length;
        for(var t=0;t<appData.player.length;t++)
            for(var a=0;a<e.all_gamer_info.length;a++)
                if(appData.player[t].serial_num==e.all_gamer_info[a].serial_num){
                    appData.player[t].nickname=e.all_gamer_info[a].nickname;
                    appData.player[t].headimgurl=e.all_gamer_info[a].headimgurl;
                    appData.player[t].account_id=e.all_gamer_info[a].account_id;
                    appData.player[t].account_score=Math.ceil(e.all_gamer_info[a].account_score);
                    appData.player[t].account_status=Math.ceil(e.all_gamer_info[a].account_status);
                    appData.player[t].online_status=Math.ceil(e.all_gamer_info[a].online_status);
                    appData.player[t].ticket_checked=e.all_gamer_info[a].ticket_checked;
                }
        appData.player[0].card=e.data.cards.concat();
        appData.player[0].card_type=e.data.card_type;
    },
    processAllGamerInfo:function(e){
        for(var t=0;t<9;t++)
            for(var a=0;a<e.data.length;a++)
                if(appData.player[t].serial_num==e.data[a].serial_num){
                    appData.player[t].is_guest=0;    //观战功能
                    appData.player[t].nickname=e.data[a].nickname;
                    appData.player[t].headimgurl=e.data[a].headimgurl;
                    appData.player[t].account_id=e.data[a].account_id;
                    appData.player[t].account_score=Math.ceil(e.data[a].account_score);
                    appData.player[t].account_status=Math.ceil(e.data[a].account_status);
                    8==appData.player[t].account_status&&(appData.player[t].account_status=4);
                    appData.player[t].online_status=Math.ceil(e.data[a].online_status);
                    appData.player[t].ticket_checked=e.data[a].ticket_checked
                }

        appData.player[0].account_status>2&&setTimeout(function(){appData.player[0].is_showCard=!0},500);

        if(""!=appData.scoreboard){
            for(var t=0;t<9;t++)
                for(s in appData.scoreboard)
                    if(appData.player[t].account_id==s){
                        appData.playerBoard.score[t].num=appData.player[t].num;
                        appData.playerBoard.score[t].account_id=appData.player[t].account_id;
                        appData.playerBoard.score[t].nickname=appData.player[t].nickname;
                        appData.playerBoard.score[t].account_score=Math.ceil(appData.scoreboard[s]);
                    }

            if(2==appData.game.status){
                appData.playerBoard.round=appData.game.round-1;
            } else {
                appData.playerBoard.round=appData.game.round;
            }
        }
        appData.player[0].account_status>2&&setTimeout(function(){appData.player[0].is_showCard=!0},500)
    },
    processUpdateGamerInfo:function(e){

        var has_seat = false;    //观战功能
        for(var t=0;t<9;t++)
            if(appData.player[t].serial_num==e.data.serial_num){
                appData.player[t].nickname=e.data.nickname;
                appData.player[t].headimgurl=e.data.headimgurl;
                appData.player[t].account_id=e.data.account_id;
                appData.player[t].account_score=Math.ceil(e.data.account_score);
                appData.player[t].account_status=Math.ceil(e.data.account_status);
                appData.player[t].online_status=Math.ceil(e.data.online_status);
                appData.player[t].ticket_checked=e.data.ticket_checked;
                appData.player[t].is_guest=0;   //观战功能
            } else {
                if(appData.player[t].account_id==e.data.account_id){
                    socketModule.sendRefreshRoom();
                }
                //观战功能  有位置
                if(appData.player[t].account_id == userData.accountId || 0==appData.player[t].account_id){
                    has_seat = true;
                }
            }
        //观战功能  
        appData.showSitdownButton = appData.isWatching && has_seat;
        //观战功能  加入游戏的玩家从观战者列表中剔除
        for(a=0;a<appData.guests.length;a++)
            if(appData.guests[a].account_id==e.data.account_id){
                break;
            }
        appData.guests.splice(a,1);
    },
    processUpdateAccountStatus:function(e){
        for(var i=0;i<9;i++){
            if(appData.player[i].account_id==e.data.account_id){
                if(1==e.data.online_status){
                    appData.player[i].account_status=Math.ceil(e.data.account_status);
                    0!=i?
                    4==appData.player[i].account_status?m4aAudioPlay("audio3"):
                    5==appData.player[i].account_status?m4aAudioPlay("audio4"):
                    6==appData.player[i].account_status&&m4aAudioPlay("audio5"):
                    appData.player[0].is_operation=!1;
                } else {
                    appData.player[i].online_status=0;
                    appData.player[i].account_status=Math.ceil(e.data.account_status);
                    
                    //观战功能   在座玩家观战中离线
                    for(a=0;a<appData.guests.length;a++)
                        if(appData.guests[a].account_id==e.data.account_id){
                            break;
                        }
                    appData.guests.splice(a,1);

                    if(0==appData.player[i].account_status){
                        //观战功能 有位置可加入
                        appData.showSitdownButton = appData.isWatching;

                        appData.player[i].account_id=0;
                        appData.player[i].playing_status=0;
                        appData.player[i].nickname="";
                        appData.player[i].headimgurl="";
                        appData.player[i].account_score=0;
                    } 
                }
            }
        }
        if(9 == i){ //观战功能  观战者离线
            for(a=0;a<appData.guests.length;a++)
                if(appData.guests[a].account_id==e.data.account_id){
                    break;
                }
            appData.guests.splice(a,1);
        }
    },
    processStartLimitTime:function(e){e.data.limit_time>1&&(appData.game.time=Math.ceil(e.data.limit_time),viewMethods.timeCountDown())},
    processCancelStartLimitTime:function(e){appData.game.time=-1},
    processGameStart:function(e){
        viewMethods.tableReset(0);
        appData.game.score=0;
        appData.game.time=-1;
        appData.game.is_play=!0;
        appData.game.round=appData.game.round+1;
        appData.game.curr_circle=1;
        currentPlayerNum=-1;
        for(var t=0;t<9;t++){
            appData.player[t].is_operation=!1,
            appData.player[t].is_showCard=!1;
            for(var a=0;a<e.data.length;a++)
                if(appData.player[t].account_id==e.data[a].account_id){
                    appData.player[t].ticket_checked=1,
                    appData.player[t].account_status=Math.ceil(e.data[a].account_status),
                    appData.player[t].playing_status=Math.ceil(e.data[a].playing_status),
                    appData.player[t].online_status=Math.ceil(e.data[a].online_status),
                    appData.player[t].account_score = appData.player[t].account_score-appData.ruleInfo.default_score,
                    appData.player[t].limit_time=Math.ceil(e.data[a].limit_time);

                    if(appData.player[t].playing_status>1){
                        currentPlayerNum=t;
                    }
                    appData.game.score=appData.game.score + appData.ruleInfo.default_score;
                    viewMethods.throwCoin(0,appData.ruleInfo.default_score);
                }
        }
        appData.game.status=2;
        viewMethods.reDeal();
        currentPlayerNum>=0&&viewMethods.playerTimeCountDown();
    },
    processNotyChooseChip:function(e){
        appData.game.is_play=!0;
        currentPlayerNum=-1;
        if(2==appData.game.status){
            for(var t=0;t<9;t++){
                appData.player[t].playing_status=1;
                if(appData.player[t].account_id==e.data.account_id){
                    appData.player[t].is_showCard=!0;
                    appData.player[t].is_operation=!1;
                    appData.player[t].playing_status=Math.ceil(e.data.playing_status);
                    appData.player[t].limit_time=Math.ceil(e.data.limit_time);
                    appData.game.can_open=e.data.can_open;
                    console.log("can_open:"+e.data.can_open);
                }
                if(appData.player[t].playing_status>1){
                    currentPlayerNum=t;
                }
            }
        }

        if(parseInt(e.data.curr_circle)+1>appData.game.curr_circle){
            appData.game.curr_circle=parseInt(e.data.curr_circle)+1;
        }
        appData.pkPeople=e.data.pk_user.concat();
        if(currentPlayerNum>=0){
            viewMethods.playerTimeCountDown();
        }
    },
    processCardInfo:function(e){appData.player[0].card=e.data.cards.concat(),appData.player[0].card_type=e.data.card_type,viewMethods.cardOver(0),viewMethods.cardTest()},
    processPKCard:function(e){for(var t=0,a=0,n=0;n<9;n++)appData.player[n].account_id==e.data.account_id&&(appData.player[n].account_score=appData.player[n].account_score-Math.ceil(e.data.score),viewMethods.throwCoin(appData.player[n].num,e.data.score)),appData.player[n].account_id==e.data.loser_id&&(appData.player[n].account_status=7,appData.player[n].is_pk=!0,t=n),appData.player[n].account_id==e.data.winner_id&&(appData.player[n].is_pk=!0,a=n);appData.game.score=appData.game.score+Math.ceil(e.data.score),viewMethods.playerPK(t,a)},
    processBroadcastVoice:function(e){if(appData.player[0].account_id==userData.accountId)for(var t=0;t<9;t++)appData.player[t].account_id==e.data.account_id&&0!=t&&(m4aAudioPlay("message"+e.data.voice_num),viewMethods.messageSay(t,e.data.voice_num));else for(var t=0;t<9;t++)appData.player[t].account_id==e.data.account_id&&(m4aAudioPlay("message"+e.data.voice_num),viewMethods.messageSay(t,e.data.voice_num))},

    processUpdateAccountScore:function(e){
        for(var t=0;t<9;t++)
            if(appData.player[t].account_id==e.data.account_id){
                appData.player[t].account_score=appData.player[t].account_score-Math.ceil(e.data.score);
                appData.game.score=appData.game.score+Math.ceil(e.data.score);
                
                if(0!=t ||  appData.player[0].account_id != userData.accountId){     //观战功能
                    if(appData.ruleInfo.xp_chip==e.data.score||appData.ruleInfo.xp_chip/2==e.data.score){
                        
                        if(appData.ruleInfo.xp_chip==appData.game.currentScore){
                            m4aAudioPlay(e.data.score+"f");
                        } else {
                            m4aAudioPlay("bloody");
                            audioModule.stopSound("backMusic");
                            audioModule.stopSound("zhangu");
                            audioModule.playSound("zhangu",!0);
                        }
                        viewMethods.throwCoin(appData.player[t].num,e.data.score,1)
                    } else {
                        viewMethods.throwCoin(appData.player[t].num,e.data.score);
                        m4aAudioPlay(e.data.score+"f");
                    }
                }    

                if(5==appData.player[t].account_status){
                    appData.game.currentScore=2*Math.ceil(e.data.score)
                } else {
                    appData.game.currentScore=Math.ceil(e.data.score)
                }
            }
    },
    processOpenCard:function(e){
        if(!appData.game.is_play)
            return 0;
        for(var t=0;t<9;t++)
            if(appData.player[t].account_id==e.data.account_id){
                appData.player[t].account_score=appData.player[t].account_score-Math.ceil(e.data.score);
                appData.game.score=appData.game.score+Math.ceil(e.data.score);

                if(appData.ruleInfo.xp_chip == appData.game.currentScore){
                    viewMethods.throwCoin(appData.player[t].num,e.data.score, 1);
                } else {
                    viewMethods.throwCoin(appData.player[t].num,e.data.score);
                }
                
            }
    },
    processWin:function(e){
        appData.game.is_play=!1,
        appData.game.round=parseInt(e.data.game_num),
        appData.game.total_num=parseInt(e.data.total_num),
        appData.playerBoard.round=parseInt(e.data.game_num);
        for(var t=0;t<9;t++){
            if(appData.player[t].playing_status=1,0==e.data.card_type){}
            else {
                for (var a = 0; a < e.data.player_cards.length; a++) {
                    appData.player[t].account_id == e.data.player_cards[a].account_id && (appData.player[t].card = e.data.player_cards[a].cards.concat());
                }
            }
            for(a in e.data.winner_score_dict) {
                appData.player[t].account_id == a && (appData.player[t].is_win = !0, appData.player[t].win_type = e.data.card_type, appData.player[t].current_win = e.data.winner_score_dict[a])
            }
            if (e.data.xipai_score_dict[appData.player[t].account_id] && e.data.card_type >= 5 && appData.ruleInfo.xipai_score > 0) {
                appData.player[t].xipai_score = e.data.xipai_score_dict[appData.player[t].account_id];
                appData.player[t].is_xipai = true;
            }
        }
        
        if(0==e.data.card_type){
            viewMethods.gameOver(e.data.winner_score_dict,e.data.score_board,1e3,2e3,e.data.balance_scoreboard)
        } else {
            viewMethods.cardOver(1);
            if(e.data.total_num==e.data.game_num){
                viewMethods.gameOver(e.data.winner_score_dict,e.data.score_board,2500,1e3,e.data.balance_scoreboard)
            } else {
                viewMethods.gameOver(e.data.winner_score_dict,e.data.score_board,2500,2500,e.data.balance_scoreboard)
            }
        }
        if(e.data.total_num==e.data.game_num){
            viewMethods.roundEnd()
        }
    },
    processDiscard:function(e){appData.player[0].account_status=6},
    processLastScoreboard:function(e){if(void 0!=e){console.log(e);try{var t=new Date(1e3*parseInt(e.time)),a=t.getFullYear()+"-",n=t.getMonth()+1+"-",o=t.getDate()+" ",i=t.getHours(),r=t.getMinutes(),c=":";r<10&&(c+=0);var l=a+n+o+i+c+r;appData.playerBoard.round=e.game_num,appData.playerBoard.record=l,appData.playerBoard.score=[],void 0!=e.total_num&&null!=e.total_num&&""!=e.total_num&&(appData.game.total_num=e.total_num);var u=e.scoreboard;for(s in u){var p=0;userData.accountId==u[s].account_id&&(p=1),appData.playerBoard.score.push({account_id:u[s].account_id,nickname:u[s].name,account_score:Math.ceil(u[s].score),num:p})}chooseBigWinner(),$(".ranking .rankBack").css("opacity","1"),$(".roundEndShow").show(),$(".ranking").show(),canvas(),$("#endCreateRoomBtn").show()}catch(e){console.log(e)}}},
    
    //观战功能
    processGuestRoom:function(e){
        appData.game.room=e.data.room_id;
        appData.game.round=Math.ceil(e.data.game_num);
        appData.game.total_num=Math.ceil(e.data.total_num);
        appData.game.score=Math.ceil(e.data.pool_score);
        appData.game.status=Math.ceil(e.data.room_status);
        appData.game.creator_id = Math.ceil(e.data.creator_id);
        appData.game.currentScore = Math.ceil(e.data.benchmark);

        if(2==appData.game.status){
            appData.game.cardDeal=3;
        }
        
        appData.scoreboard=e.data.scoreboard;
        viewMethods.clickCloseAlert();
        appData.showGuest=0;
    },
    processAllGuestInfo:function(e){
        appData.guests=[];
        if(e.data){
            for(var t=0;t<e.data.length;t++){
                appData.guests.push({
                    account_id:e.data[t].account_id,
                    avatar:e.data[t].headimgurl,
                    nickname:e.data[t].nickname
                });
                for(var a=0;a<appData.player.length;a++)
                    if(appData.player[a].account_id==e.data[t].account_id){
                        appData.player[a].is_guest=1;
                        if(appData.player[a].account_status<1){
                            appData.player[a].account_id=0;
                        }
                    }
            }
        }
        appData.isWatching=0;
        for(var i=0;i<appData.guests.length;i++)
            if(appData.guests[i].account_id==userData.accountId){
                appData.isWatching=1;
            }
        console.log(appData.player);
    },
    processUpdateGuestInfo:function(e){
        for(a=0;a<appData.guests.length;a++)
            if(appData.guests[a].account_id==e.data.account_id){
                break;
            }
        if(e.data.is_guest == 1){
            if(a == appData.guests.length){
                appData.guests.push({
                    account_id:e.data.account_id,
                    avatar:e.data.headimgurl,
                    nickname:e.data.nickname
                });
            }
            for(var n=0;n<appData.player.length;n++)
                if(appData.player[n].account_id==e.data.account_id){
                    appData.player[n].is_guest=1;
                    if(appData.player[n].account_status<1){
                        appData.player[n].account_id=0;

                        appData.showSitdownButton = appData.isWatching;
                    }
                }
        } else {
            appData.guests.splice(a,1);
        }
    },
};
var viewMethods={
    clickShowAlert:function(e,t){console.log(e,t),appData.alertType=e,appData.alertText=t,appData.isShowAlert=!0,setTimeout(function(){var t=$(".alertText").height(),a=t
;t<.15*height&&(t=.15*height),t>.8*height&&(t=.8*height);var n=t+.056*height*2+.022*height+.056*height;8==e&&(n=n-.022*height-.056*height);var o=t+.034*height*2,i=.022*height+(o-a)/2;$(".alert .mainPart").css("height",n+"px"),$(".alert .mainPart").css("margin-top","-"+n/2+"px"),$(".alert .mainPart .backImg .blackImg").css("height",o+"px"),$(".alert .mainPart .alertText").css("top",i+"px")},0)},
    clickCloseAlert:function(){
        22==appData.alertType?
        (appData.isShowAlert=!1,httpModule.getInfo()):
        appData.isShowAlert=!1
    },
    clickSitDown:function(){appData.isShowAlert=!1,socketModule.sendJoinRoom()},
    clickReady:function(){if(appData.player[0].is_operation||1!=appData.game.status)return 0;socketModule.sendReadyStart(),appData.player[0].is_operation=!0},
    clickCloseRoom: function() {
        socketModule.sendCloseRoom();
        appData.player[0].is_operation = true;
    },
    reDeal:function(){m4aAudioPlay("audio1"),appData.game.cardDeal=1,setTimeout(function(){appData.game.cardDeal=2,setTimeout(function(){appData.game.cardDeal=3,setTimeout(function(){appData.player[0].is_showCard=!0},400)},250)},250)},
    cardOver:function(e){0==e?($(".myCards .card0").velocity({left:0},{duration:450}),$(".myCards .card1").velocity({left:0},{duration:450}),$(".myCards .card2").velocity({left:0},{duration:450,complete:function(){$(".myCards .cards").addClass("card-flipped"),$(".myCards .card0").velocity({left:"0"},{duration:550}),$(".myCards .card1").velocity({left:"50%"},{duration:550}),$(".myCards .card2").velocity({left:"100%"},{duration:550})}})):(appData.game.cardDeal=-1,$(".cardOver .card0").velocity({left:0},{duration:250}),$(".cardOver .card1").velocity({left:0},{duration:250}),$(".cardOver .card2").velocity({left:0},{duration:250,complete:function(){$(".cardOver .cards").addClass("card-flipped"),$(".cardOver .card0").velocity({left:"0"},{duration:500}),$(".cardOver .card1").velocity({left:"25%"},{duration:500}),$(".cardOver .card2").velocity({left:"50%"},{duration:500})}}),5==appData.player[0].account_status&&(appData.player[0].account_status=4,viewMethods.cardOver(0)))},
    cardTest:function(){4==appData.player[0].account_status&&0==appData.player[0].card.length&&socketModule.sendRefreshRoom()},
    gameOver:function(e,t,a,n){
        appData.playerBoard.score=[];
        for(s in t)
            for(var o=0;o<9;o++)
                if(appData.player[o].account_id==s){
                    appData.player[o].account_score=Math.ceil(t[s]);
                    appData.playerBoard.score.push({
                        num:appData.player[o].num,
                        account_id:appData.player[o].account_id,
                        nickname:appData.player[o].nickname,
                        account_score:parseInt(appData.player[o].account_score)
                    });
                }

        //appData.playerBoard.score=appData.playerBoard.score.sort(by("account_score")).concat();
        setTimeout(function(){
            var e=0;
            for(var a=0;a<appData.player.length;a++)
                if(appData.player[a].is_win){
                    appData.player[a].win_show=!0;
                    if(0==a){
                        mp3AudioPlay("win");
                    }
                    if(0==e){
                        e=1;
                        numD=appData.player[a].num;
                        setTimeout(function(){
                            viewMethods.selectCoin(numD,t)
                        },1500);
                    }
                }
            var o=new Date,i="";
            i+=o.getFullYear()+"-",
            i+=o.getMonth()+1+"-",
            i+=o.getDate()+"  ",
            i+=o.getHours()+":",
            o.getMinutes()>=10?i+=o.getMinutes():i+="0"+o.getMinutes(),
            appData.playerBoard.record=i,
            setTimeout(function(){
                audioModule.stopSound("backMusic"),
                audioModule.stopSound("zhangu"),
                audioModule.playSound("backMusic",!0),
                viewMethods.tableReset(1)
            },n)
        },a)
    },
    showMessage:function(){appData.player[0].account_id==userData.accountId&&(appData.isShowMessage=!0,disable_scroll(),setTimeout(function(){appData.bScroll?appData.bScroll.refresh():appData.bScroll=new BScroll(document.getElementById("message-box"),{startX:0,startY:0,scrollY:!0,scrollX:!1,click:!0})},10))},
    hideMessage:function(){appData.isShowMessage=!1,enable_scroll()},
    messageOn:function(e){socketModule.sendBroadcastVoice(e),m4aAudioPlay("message"+e),viewMethods.messageSay(0,e),viewMethods.hideMessage()},
    messageSay:function(e,t){appData.player[e].messageOn=!0,appData.player[e].messageText=appData.message[t].text,setTimeout(function(){appData.player[e].messageOn=!1},2500)},
    closeEnd:function(){$(".ranking .rankBack").css("opacity","0.7"),$(".end").hide(),$(".roundEndShow").hide(),$(".ranking").hide(),reload()},
    roundEnd:function(){for(var e=0;e<appData.player.length;e++)0==appData.player[e].online_status&&(appData.player[e].account_id=0,appData.player[e].playing_status=0,appData.player[e].online_status=0,appData.player[e].nickname="",appData.player[e].headimgurl="",appData.player[e].account_score=0),appData.player[e].ticket_checked=0;chooseBigWinner(),$(".ranking .rankBack").css("opacity","1"),$(".roundEndShow").show(),setTimeout(function(){$(".ranking").show(),canvas()},3500)},
    timeCountDown:function(){if(1!=isTimeLimitShow)return appData.game.time<=0?(isTimeLimitShow=!1,0):(isTimeLimitShow=!0,appData.game.time--,timeLimit=setTimeout(function(){isTimeLimitShow=!1,viewMethods.timeCountDown()},1e3),void 0)},
    playerTimeCountDown:function(){if(1!=isPlayerTimeLimitShow)return appData.player[currentPlayerNum].limit_time<=0||currentPlayerNum<0?(isPlayerTimeLimitShow=!1,0):(isPlayerTimeLimitShow=!0,appData.player[currentPlayerNum].limit_time--,setTimeout(function(){isPlayerTimeLimitShow=!1,viewMethods.playerTimeCountDown()},1e3),void 0)},
    tableReset:function(e){
        for(var t=0;t<9;t++){
            if(appData.player[t].account_status>1&&1==e){
                appData.player[t].account_status=1;
            }
            appData.player[t].playing_status=0;
            appData.player[t].is_win=!1;
            appData.player[t].is_operation=!1;
            appData.player[t].win_type=0;
            appData.player[t].win_show=!1;
            appData.player[t].card=[];
            appData.player[t].card_type=0;
            appData.player[t].is_showCard=!1;
            appData.player[t].is_readyPK=!1;
            appData.player[t].is_pk=!1;
            appData.player[t].is_xipai = false;
        }
        appData.game.can_open=0;appData.game.score=0;
        appData.game.cardDeal=0;
        appData.game.currentScore=0;
        appData.game.status=1;
        appData.game.curr_circle=0;
        $(".cards").removeClass("card-flipped");
        $(".scoresArea").empty();
    },
    throwCoin:function(e,t,a){
        return 1==a?
        (
            $(".scoresArea").append("<div class='coin coin"+e+" coinBloody"+t+" coinBloody coinBloodyR"+Math.round(12*Math.random())+"'  ></div>"),
            void $(".coin"+e).velocity({
                top:(30*perW-28)*Math.random(),
                left:(30*perW-28)*Math.random()
            },{
                duration:0,
                complete:function(){
                    $(".coin").removeClass("coin"+e)
                }
            })
        ):
        0==e?
        (
            $(".scoresArea").append("<div class='coin coinType"+t+"' style='top:"+(30*perW-28)*Math.random()+"px;left:"+(30*perW-28)*Math.random()+"px;' ></div>"),
            0
        ):
        (
            $(".scoresArea").append("<div class='coin coin"+e+" coinType"+t+"' ></div>"),
            void $(".coin"+e).velocity({
                top:(30*perW-28)*Math.random(),
                left:(30*perW-28)*Math.random()
            },{
                duration:0,
                complete:function(){
                    $(".coin").removeClass("coin"+e)
                }
            })
        )
    },
    selectCoin:function(e,t){var a=0,n=0;1==e?(a="36vh",n=40):2==e?(a="23vh",n=150):3==e?(a="10vh",n=150):4==e?(a="-4vh",n=150):5==e?(a="-16vh",n=110):6==e?(a="-16vh",n=-40):7==e?(a="-4vh",n=-60):8==e?(a="10vh",n=-60):9==e&&(a="23vh",n=-60),$(".coin").css("top",a),$(".coin").css("left",n),setTimeout(function(){$(".scoresArea").empty()},350)},
    playerPK:function(e,t){
        $(".pk1").css("left","-60%"),
        $(".pk2").css("right","-60%"),
        $(".playerPK .quitBack").hide(),
        $(".playerPK .background").attr("src",globalData.fileUrl+"files/images/flower/comB.png"),
        appData.turn=0==e?t<5?0:1:t<e?0:1;
        logMessage(e,t);
        if(0==appData.turn){
            appData.pk1.nickname=appData.player[e].nickname;
            appData.pk1.headimgurl=appData.player[e].headimgurl;
            appData.pk1.account_score=appData.player[e].account_score;
            appData.pk1.account_status=appData.player[e].account_status;
            appData.pk2.nickname=appData.player[t].nickname;
            appData.pk2.headimgurl=appData.player[t].headimgurl;
            appData.pk2.account_score=appData.player[t].account_score;
            appData.pk2.account_status=appData.player[t].account_status;
        } else {
            appData.pk1.nickname=appData.player[t].nickname;
            appData.pk1.headimgurl=appData.player[t].headimgurl;
            appData.pk1.account_score=appData.player[t].account_score;
            appData.pk1.account_status=appData.player[t].account_status;
            appData.pk2.nickname=appData.player[e].nickname;
            appData.pk2.headimgurl=appData.player[e].headimgurl;
            appData.pk2.account_score=appData.player[e].account_score;
            appData.pk2.account_status=appData.player[e].account_status;
        }
        appData.pk.round=2;
        setTimeout(function(){
            m4aAudioPlay("com");
            $(".pk1").velocity({left:0},{duration:500});
            $(".pk2").velocity({right:0},{duration:500,complete:function(){
                appData.pk.round=3;
                setTimeout(function(){
                    appData.pk.round=4;
                    if(7==appData.pk1.account_status){
                        $(".pk1 .quitBack").fadeIn();
                        $(".pk1 .background").attr("src",globalData.fileUrl+"files/images/common/player_bg.png");
                    } else {
                        $(".pk1 .background").attr("src",globalData.fileUrl+"files/images/common/player_selected.png");
                    }
                    
                    if(7==appData.pk2.account_status){
                        $(".pk2 .quitBack").fadeIn();
                        $(".pk2 .background").attr("src",globalData.fileUrl+"files/images/common/player_bg.png");
                    } else {
                        $(".pk2 .background").attr("src",globalData.fileUrl+"files/images/common/player_selected.png")
                    }

                    setTimeout(function(){
                        appData.pk.round=0;
                        for(var e=0;e<appData.player.length;e++)
                            appData.player[e].is_pk=!1
                    },2e3);
                },800)
            }});
        },0)
    },
    choose:function(e,t){
        if(appData.player[0].is_operation)
            return 0;
        if(1==e)
            socketModule.sendClickToLook(),m4aAudioPlay("audio3");
        else if(2==e){
            socketModule.sendChooseChip(t);
            console.log("here:"+appData.ruleInfo.xp_chip);
            console.log("ihere t:"+t);
            if(appData.ruleInfo.xp_chip==t||appData.ruleInfo.xp_chip/2==t){

                if(appData.ruleInfo.xp_chip==appData.game.currentScore){
                    m4aAudioPlay(t+"f")
                } else {    //血拼
                    m4aAudioPlay("bloody");
                    audioModule.stopSound("backMusic");
                    audioModule.stopSound("zhangu");
                    audioModule.playSound("zhangu",!0);
                }
                viewMethods.throwCoin(1,t,1);
                if(appData.ruleInfo.xp_chip!=appData.game.currentScore){
                    appData.roomCard=appData.roomCard-appData.ruleInfo.bloody_chip_ticket;
                }
            } else {
                m4aAudioPlay(t+"f");
                viewMethods.throwCoin(1,t);
            }
            appData.player[0].is_operation=!0;
        }
        else if(3==e)
            socketModule.sendDiscard(),m4aAudioPlay("audio5"),appData.player[0].is_operation=!0;
        else if(4==e){
            for(var a=0,n=0;n<appData.player.length;n++)
                4!=appData.player[n].account_status&&5!=appData.player[n].account_status||a++;
            if(2==a)
                socketModule.sendOpenCard(),m4aAudioPlay("audio2"),appData.player[0].is_operation=!0;
            else{
                for(var n=0;n<appData.player.length;n++){
                    appData.player[n].is_readyPK=!1;
                    for(var o=0;o<appData.pkPeople.length;o++)
                        appData.player[n].account_id==appData.pkPeople[o]&&(appData.player[n].is_readyPK=!0)
                }
                appData.pk.round=1
            }
        }
        else 5==e&&(socketModule.sendPkCard(t),appData.player[0].is_operation=!0)
    },
    quitPk:function(){appData.pk.round=0}
};
var width=window.innerWidth;
var height=window.innerHeight;
var numD=0;
var isTimeLimitShow=!1;
var isPlayerTimeLimitShow=!1;
var currentPlayerNum=0;
var ruleInfo={
    type:0,
    isShow:!1,
    isShowRule:!1,
    ticket_count:1,
    disable_pk:0,

    rule_height:60,
   
    bloody_chip_ticket:0,
    bloody_chip_tip:"",
    
    default_score:0,
    bet_circle:10,
    look_cond:0,
    pk_cond:1,
    xp_cond:1, //血拼条件 第几轮之后
    xp_circle:1, //血拼圈数
    xp_chip:120,
    xipai_score:0,
};
var editAudioInfo={
        isShow:!1,
        backMusic:1,
        messageMusic:1
    };
var audioInfo={
    backMusic:1,
    messageMusic:1
};
localStorage.backMusic?
(editAudioInfo.backMusic=localStorage.backMusic,audioInfo.backMusic=localStorage.backMusic):
localStorage.backMusic=1,
localStorage.messageMusic?
(editAudioInfo.messageMusic=localStorage.messageMusic,audioInfo.messageMusic=localStorage.messageMusic):
localStorage.messageMusic=1;

var appData={
    //观战功能
    isWatching:0,
    guests:[],
    showGuest:0,
    showSitdownButton:0,
    showWatchButton:1,
    joinType:0,

    user_id:userData.id,
    roomStatus:globalData.roomStatus,
    scoreList1:[4,8,16,20],
    scoreList2:[2,4,8,10],
    width:window.innerWidth,
    height:window.innerHeight,
    roomCard:Math.ceil(globalData.card),
    is_connect:!1,
    player:[],
    scoreboard:"",
    activity:[],
    isShowAlert:!1,
    isShowMessage:!1,
    alertType:0,
    alertText:"",

    playerBoard:{
        score:[],
        round:0,
        record:""
    },
    game:game,
    roomCardInfo:[],
    wsocket:ws,
    connectOrNot:!0,
    socketStatus:0,
    heartbeat:null,
    select:1,
    ticket_count:0,
    isDealing:!1,
    message:message,
    pkPeople:[],
    turn:0,
    pk:{turn:0,round:0},
    pk1:{
        nickname:"",
        headimgurl:"",
        account_score:0,
        account_status:0},
    pk2:{
        nickname:"",
        headimgurl:"",
        account_score:0,
        account_status:0
    },
    ruleInfo:ruleInfo,
    editAudioInfo:editAudioInfo,
    audioInfo:audioInfo,

    isReconnect:!0,
    bScroll:null,
    //广播
    isShowNoty:false,
    notyMsg:"",

    isShowNoteImg:!1
};


//广播 
setTimeout(function () {
    if (globalData.isNotyMsg != undefined && globalData.isNotyMsg != null) {
        appData.notyMsg = globalData.notyMsg;
        if (globalData.isNotyMsg == 1) {
            appData.isShowNoty = true;
            setTimeout(function () {
                appData.isShowNoty = false;
            }, globalData.notyTime * 1000);
        }
    } else {
        globalData.isNotyMsg = 0;
    }
    $('#marquee').marquee({
        //speed in milliseconds of the marquee
        duration: globalData.notySpeed,
        //gap in pixels between the tickers
        gap: 400,
        //time in milliseconds before the marquee will start animating
        delayBeforeStart: 0,
        //'left' or 'right'
        direction: 'left',
        //true or false - should the marquee be duplicated to show an effect of continues flow
        duplicated: true
    });

}, 50);
//end 广播

var resetState=function(){
    appData.player=[],
    appData.playerBoard={
        score:[],
        round:0,
        record:""
    };
    for(var e=0;e<9;e++)
        appData.player.push({
            num:e+1,
            serial_num:e+1,
            account_id:0,
            account_status:0,
            playing_status:0,
            online_status:0,
            nickname:"",
            headimgurl:"",
            account_score:0,
            ticket_checked:0,
            is_win:!1,
            win_type:0,
            limit_time:0,
            current_win:0,
            is_operation:!1,
            win_show:!1,
            card:[],
            is_showCard:!1,
            is_pk:!1,
            is_readyPK:!1,
            card_type:0,
            messageOn:!1,
            messageText:"我们来血拼吧",
            is_guest:0,
            "is_xipai": false,
            "xipai_score": 0,
        }),
        appData.playerBoard.score.push({
            account_id:0,nickname:"",
            account_score:0,
            isBigWinner:0
        });
    httpModule.getInfo()




};
var newGame=function(){
    appData.playerBoard={
        score:[],
        round:0,
        record:""
    };
    appData.game.round=0;
    appData.game.status=1;
    appData.game.score=0;
    appData.game.currentScore=0;
    appData.game.cardDeal=0;
    appData.game.can_open=0;
    appData.game.is_play=!1;
    for(var e=0;e<appData.player.length;e++)
        appData.playerBoard.score.push({
            account_id:0,
            nickname:"",
            account_score:0,
            isBigWinner:0
        }),
        1==appData.player[e].online_status?
        (appData.player[e].account_status=0,appData.player[e].playing_status=0,appData.player[e].is_win=!1,appData.player[e].is_operation=!1,appData.player[e].win_type=0,appData.player[e].win_show=!1,appData.player[e].card=[],appData.player[e].card_type=0,appData.player[e].ticket_checked=0,appData.player[e].account_score=0,appData.player[e].current_win=0,appData.player[e].is_showCard=!1,appData.player[e].is_readyPK=!1,appData.player[e].is_pk=!1):
        appData.player[e]={num:e+1,serial_num:appData.player[e].serial_num,account_id:0,account_status:0,playing_status:0,online_status:0,nickname:"",headimgurl:"",account_score:0,is_win:!1,win_type:0,ticket_checked:0,limit_time:0,current_win:0,is_operation:!1,win_show:!1,card:[],is_showCard:!1,is_pk:!1,is_readyPK:!1,card_type:0,is_guest:0}
};
var connectSocket=function(e,t,a,n,o){
    ws=new WebSocket(e),ws.onopen=t,ws.onmessage=a,ws.onclose=n,ws.onerror=o
};
var wsOpenCallback=function(e){logMessage("websocket is opened"),appData.connectOrNot=!0,appData.heartbeat&&clearInterval(appData.heartbeat),appData.heartbeat=setInterval(function(){appData.socketStatus=appData.socketStatus+1,appData.socketStatus>2&&(appData.connectOrNot=!1),appData.socketStatus>3&&appData.isReconnect&&reload(),ws.readyState==WebSocket.OPEN&&ws.send("@")},3e3),socketModule.sendPrepareJoinRoom()};
var wsMessageCallback=function wsMessageCallback(evt){
    if(appData.connectOrNot=!0,"@"==evt.data)return appData.socketStatus=0,0;var obj=eval("("+evt.data+")");
    if(-201==obj.result)viewMethods.clickShowAlert(31,obj.result_message);
    else if(-202==obj.result)appData.isReconnect=!1,socketModule.closeSocket(),viewMethods.clickShowAlert(32,obj.result_message);
    else if(-203==obj.result)methods.reloadView();
    else{
        if(204==obj.result)return void socketModule.sendPrepareJoinRoom();
        if(205==obj.result)return void viewMethods.clickShowAlert(66,"欢乐豆不足.");
        if(206==obj.result)return void viewMethods.clickShowAlert(66,"您不是此公会成员.")
    }
    0!=obj.result?
    (obj.operation==wsOperation.JoinRoom?
        1==obj.result?1==obj.data.alert_type?viewMethods.clickShowAlert(1,obj.result_message):
        2==obj.data.alert_type?viewMethods.clickShowAlert(2,obj.result_message):
        3==obj.data.alert_type?viewMethods.clickShowAlert(11,obj.result_message):
        viewMethods.clickShowAlert(7,obj.result_message):
        (obj.result,viewMethods.clickShowAlert(7,obj.result_message)):
    obj.operation==wsOperation.ReadyStart?
        1==obj.result?viewMethods.clickShowAlert(1,obj.result_message):viewMethods.clickShowAlert(7,obj.result_message):
    obj.operation==wsOperation.PrepareJoinRoom?
        (obj.result>0&&socketModule.processGameRule(obj),
            1==obj.result?1==obj.data.alert_type?viewMethods.clickShowAlert(1,obj.result_message):
            2==obj.data.alert_type?viewMethods.clickShowAlert(2,obj.result_message):
            3==obj.data.alert_type?viewMethods.clickShowAlert(11,obj.result_message):
            viewMethods.clickShowAlert(7,obj.result_message):
            (obj.result,viewMethods.clickShowAlert(7,obj.result_message))):

    obj.operation==wsOperation.RefreshRoom&&reload(),appData.player[0].is_operation=!1):
    obj.operation==wsOperation.PrepareJoinRoom?socketModule.processPrepareJoinRoom(obj):
    
    obj.operation==wsOperation.JoinRoom?socketModule.processJoinRoom(obj):
    obj.operation==wsOperation.RefreshRoom?socketModule.processRefreshRoom(obj):
    obj.operation==wsOperation.AllGamerInfo?socketModule.processAllGamerInfo(obj):
    obj.operation==wsOperation.UpdateGamerInfo?socketModule.processUpdateGamerInfo(obj):
    obj.operation==wsOperation.UpdateAccountStatus?socketModule.processUpdateAccountStatus(obj):

    obj.operation==wsOperation.StartLimitTime?socketModule.processStartLimitTime(obj):
    obj.operation==wsOperation.CancelStartLimitTime?socketModule.processCancelStartLimitTime(obj):
    obj.operation==wsOperation.GameStart?socketModule.processGameStart(obj):
    obj.operation==wsOperation.NotyChooseChip?socketModule.processNotyChooseChip(obj):
    obj.operation==wsOperation.UpdateAccountScore?socketModule.processUpdateAccountScore(obj):
    obj.operation==wsOperation.OpenCard?socketModule.processOpenCard(obj):
    obj.operation==wsOperation.Win?socketModule.processWin(obj):
    obj.operation==wsOperation.Discard?socketModule.processDiscard(obj):
    obj.operation==wsOperation.BroadcastVoice?socketModule.processBroadcastVoice(obj):
    obj.operation==wsOperation.CreateRoom?socketModule.processCreateRoom(obj):
    obj.operation==wsOperation.PkCard?socketModule.processPKCard(obj):
    obj.operation==wsOperation.CardInfo?socketModule.processCardInfo(obj):
    obj.operation==wsOperation.GuestRoom?socketModule.processGuestRoom(obj):
    obj.operation==wsOperation.AllGuestInfo?socketModule.processAllGuestInfo(obj):
    obj.operation==wsOperation.UpdateGuestInfo?socketModule.processUpdateGuestInfo(obj):
    logMessage(obj.operation)
};
var wsCloseCallback=function(e){
    logMessage("websocket closed："),logMessage(e),appData.connectOrNot=!1,reconnectSocket()
};
var wsErrorCallback=function(e){logMessage("websocket onerror："),logMessage(e),appData.connectOrNot=!1};
var reconnectSocket=function(){
    if(appData.isReconnect&&4!=globalData.roomStatus){if(ws){if(logMessage(ws.readyState),1==ws.readyState)return;ws=null}logMessage("reconnectSocket"),connectSocket(globalData.socket,wsOpenCallback,wsMessageCallback,wsCloseCallback,wsErrorCallback)}
};
var m4aAudioPlay=function(e){if(!audioModule.audioOn)return 0;audioModule.playSound(e)};
var mp3AudioPlay=function(e){if(!audioModule.audioOn)return 0;audioModule.playSound(e)};
var audioModule={
    audioOn:!1,
    audioContext:null,
    audioBuffers:[],
    baseUrl:"",
    initModule:function(e){
        this.baseUrl=e,
        this.audioBuffers=[],
        window.AudioContext=window.AudioContext||window.webkitAudioContext||window.mozAudioContext||window.msAudioContext,
        this.audioContext=new window.AudioContext
    },
    stopSound:function(e){
        var t=this.audioBuffers[e];t&&t.source&&(t.source.stop(0),t.source=null)
    },
    playSound:function(e,t){
        if("backMusic"==e){
            if(0==audioInfo.backMusic)
                return
        }else if(0==audioInfo.messageMusic)return;
        var a=this.audioBuffers[e];
        if(a)try{
            void 0!=WeixinJSBridge&&WeixinJSBridge.invoke("getNetworkType",{},function(n){
            a.source=null,a.source=audioModule.audioContext.createBufferSource(),a.source.buffer=a.buffer,a.source.loop=!1;
            var o=audioModule.audioContext.createGain();
            1==t?(a.source.loop=!0,o.gain.value=1,"backMusic"==e&&(o.gain.value=.7)):o.gain.value=1,
            a.source.connect(o),
            o.connect(audioModule.audioContext.destination),
            a.source.start(0)
        })
        }catch(e){logMessage(e),a.source.start(0)}
    },
    initSound:function(e,t){
        this.audioContext.decodeAudioData(e,function(e){
            audioModule.audioBuffers[t]={name:t,buffer:e,source:null},
            "backMusic"==t&&(audioModule.audioOn=!0,appData.game.currentScore!=appData.ruleInfo.xp_chip&&audioModule.playSound(t,!0)),
            "zhangu"==t&&appData.game.currentScore==appData.ruleInfo.xp_chip&&
            (audioModule.stopSound("backMusic"),audioModule.stopSound("zhangu"),audioModule.playSound("zhangu",!0))
        },function(e){logMessage("Error decoding file",e)})
    },
    loadAudioFile:function(e,t){
        var a=new XMLHttpRequest;
        a.open("GET",e,!0),a.responseType="arraybuffer",
        a.onload=function(e){audioModule.initSound(a.response,t)},a.send()
    },
    loadAllAudioFile:function(){
        if(4!=globalData.roomStatus&&1!=isLoadAudioFile){
            isLoadAudioFile=!0,
            this.loadAudioFile(this.baseUrl+"files/audio/flower/back.mp3","backMusic");

            var e=["5f.m4a","40f.m4a","2f.m4a","4f.m4a","8f.m4a","16f.m4a","10f.m4a","20f.m4a","audio1.m4a","audio2.m4a","audio3.m4a","audio4.m4a","audio5.m4a","com.m4a","lose.mp3","win.mp3"];
            var t=["5f","40f","2f","4f","8f","16f","10f","20f","audio1","audio2","audio3","audio4","audio5","com","lose","win"];
            for(a=0;a<e.length;a++)
                this.loadAudioFile(this.baseUrl+"files/audio/flower/"+e[a],t[a]);

            var n=["50f.m4a","100f.m4a","200f.m4a","30f.m4a","60f.m4a","80f.m4a","120f.m4a","150f.m4a","160f.m4a","250f.m4a","300f.m4a","400f.m4a","500f.m4a","600f.m4a","800f.m4a","1000f.m4a","bloody.m4a","zhangu.m4a"];
            var o=["50f","100f","200f","30f","60f","80f","120f","150f","160f","250f","300f","400f","500f","600f","800f","1000f","bloody","zhangu"];
            for(a=0;a<n.length;a++)
                this.loadAudioFile(this.baseUrl+"files/audio/flower2/"+n[a],o[a]);

            var i=["message9.m4a","message10.m4a","message11.m4a","message1.m4a","message2.m4a","message3.m4a","message4.m4a","message5.m4a","message6.m4a","message7.m4a","message8.m4a"];
            var r=["message0","message1","message2","message3","message4","message5","message6","message7","message8","message9","message10"];
            for(a=0;a<i.length;a++)
                this.loadAudioFile(this.baseUrl+"files/audio/sound/"+i[a],r[a])
        }
    }
};
audioModule.initModule(globalData.fileUrl);

var initView=function(){
    $("#app-main").width(appData.width),
    $("#app-main").height(appData.height),
    $("#table").width(appData.width),
    $("#table").height(appData.height),
    $(".ranking").css("width",2*appData.width),
    $(".ranking").css("height",2*appData.width*1.621),
    window.onload=function(){
        var e=["table","vinvite","valert","vmessage","vshop","vcreateRoom","vroomRule","endCreateRoom","endCreateRoomBtn"];
        var t=e.length;
        for(a=0;a<t;a++){
            var n=document.getElementById(e[a]);
            n&&n.addEventListener("touchmove",function(e){
                e.preventDefault()
            },!1)
        }
    }
};
var methods={
    showAlert:viewMethods.clickShowAlert,
    showMessage:viewMethods.showMessage,
    closeAlert:viewMethods.clickCloseAlert,
    sitDown:viewMethods.clickSitDown,
    imReady:viewMethods.clickReady,
    imCloseRoom: viewMethods.clickCloseRoom,
    hideMessage:viewMethods.hideMessage,
    closeEnd:viewMethods.closeEnd,
    messageOn:viewMethods.messageOn,
    hall: function(){
        window.location.href = globalData.hallPath;
    },

    selectCard:viewMethods.selectCard,
    quitPk:viewMethods.quitPk,
    choose:viewMethods.choose,
    cancelCreate:function(){},
    createCommit:function(){},
    selectChange:function(e,t){},
    showGameRule:function(){4!=appData.roomStatus&&(appData.ruleInfo.isShowRule=!0)},
    cancelGameRule:function(){appData.ruleInfo.isShowRule=!1},
    
    
    showAudioSetting:function(){appData.editAudioInfo.backMusic=appData.audioInfo.backMusic,appData.editAudioInfo.messageMusic=appData.audioInfo.messageMusic,appData.editAudioInfo.isShow=!0},
    cancelAudioSetting:function(){appData.editAudioInfo.isShow=!1},
    confirmAudioSetting:function(){
        appData.editAudioInfo.isShow=!1;
        appData.audioInfo.backMusic=appData.editAudioInfo.backMusic;
        appData.audioInfo.messageMusic=appData.editAudioInfo.messageMusic;
        localStorage.backMusic=appData.editAudioInfo.backMusic;
        localStorage.messageMusic=appData.editAudioInfo.messageMusic;
        
        if(1==appData.audioInfo.backMusic){
            if(appData.ruleInfo.xp_chip!=appData.game.currentScore){
                audioModule.stopSound("backMusic");
                audioModule.playSound("backMusic",!0);
            } else {    //血拼中
                audioModule.stopSound("zhangu");
                audioModule.playSound("zhangu",!0);
            }

        } else {
            audioModule.stopSound("backMusic");
            audioModule.stopSound("zhangu");
        }
    },
    setBackMusic:function(){0==appData.editAudioInfo.backMusic?appData.editAudioInfo.backMusic=1:appData.editAudioInfo.backMusic=0},
    setMessageMusic:function(){0==appData.editAudioInfo.messageMusic?appData.editAudioInfo.messageMusic=1:appData.editAudioInfo.messageMusic=0},

    reloadView:function(){reload()},
    showNoteImg:function(){appData.isShowNoteImg=!0},
    hideNoteImg:function(){appData.isShowNoteImg=!1},
    guestRoom:function(){
        socketModule.sendGuestRoom()
    },
    hideGuests:function(){
        appData.showGuest=0
    },
    showGuests:function(){
        appData.showSitdownButton=0;
        appData.showWatchButton=!appData.isWatching && appData.player[0].account_status<2;

        if(appData.isWatching){
            for(var e=0;e<appData.player.length;e++)
                if(appData.player[e].account_id==userData.accountId || 0==appData.player[e].account_id){
                    appData.showSitdownButton = 1;
                    break
                }
        }
        appData.showGuest=1;
    }
};

var vueLife={
    vmCreated:function(){
        logMessage("vmCreated"),
        resetState(),
        initView(),
        4!=globalData.roomStatus&&$("#loading").hide(),
        $(".main").show(),
        setTimeout(function(){
            document.getElementById("tableBack").addEventListener("touchstart",function(e){
                e.preventDefault()
            },!1)
        },10)
    },
    vmUpdated:function(){
        logMessage("vmUpdated")
    },
    vmMounted:function(){logMessage("vmMounted"),$("#marquee").css("opacity",0),setTimeout(function(){$("#marquee").css("opacity",1),$("#marquee").marquee({duration:globalData.notySpeed,gap:50,delayBeforeStart:0,direction:"left",duplicated:!0})},100)},
    vmDestroyed:function(){logMessage("vmDestroyed")}
},
vm=new Vue({el:"#app-main",data:appData,methods:methods,created:vueLife.vmCreated,updated:vueLife.vmUpdated,mounted:vueLife.vmMounted,destroyed:vueLife.vmDestroyed});

function preventDefaultFn(event) {
    event.preventDefault();
}
function disable_scroll() {
    $('body').on('touchmove', preventDefaultFn);
}
function enable_scroll() {
    $('body').off('touchmove', preventDefaultFn);
}

$(function(){
    function e(){
        document[t]?
        (audioModule.audioOn=!1,audioModule.stopSound("backMusic"),audioModule.stopSound("zhangu")):
        "true"!==sessionStorage.isPaused&&
        (audioModule.audioOn=!0,audioModule.stopSound("backMusic"),audioModule.stopSound("zhangu"),
        appData.ruleInfo.xp_chip!=appData.game.currentScore?audioModule.playSound("backMusic",!0):audioModule.playSound("zhangu",!0))
    }
    $(".showRanking").click(function(){
        $(".Ranking").show()
    }),
    $(".hideRanking").click(function(){
        $(".Ranking").hide()
    }),
    sessionStorage.isPaused="false";
    var t,a;
    void 0!==document.hidden?
    (t="hidden",a="visibilitychange"):
    void 0!==document.webkitHidden&&(t="webkitHidden",a="webkitvisibilitychange"),
    void 0===document.addEventListener||void 0===t?
    alert("This demo requires a browser such as Google Chrome that supports the Page Visibility API."):
    document.addEventListener(a,e,!1)
});

function canvas() {
    var target = document.getElementById("ranking");
    html2canvas(target, {
        allowTaint: true,
        taintTest: false,
        onrendered: function(canvas) {
            canvas.id = "mycanvas";
            var dataUrl = canvas.toDataURL('image/jpeg', 0.3);
            $("#end").attr("src", dataUrl);
            $(".end").show();
            $('.ranking').hide();
            //newGame();
        }
    });
};

function chooseBigWinner() {
    var length = appData.playerBoard.score.length;
    var maxScore = 1;
    for (var i = 0; i < length; i++) {
        appData.playerBoard.score.isBigWinner = 0;
        if (appData.playerBoard.score[i].account_score > maxScore) {
            maxScore = appData.playerBoard.score[i].account_score;
        }
    }

    for (var j = 0; j < length; j++) {
        if (appData.playerBoard.score[j].account_score == maxScore) {
            appData.playerBoard.score[j].isBigWinner = 1;
        }
    }

    //对积分榜排序
    appData.playerBoard.score.sort(function(a,b){
        return b.account_score - a.account_score;
    });
};

function logMessage(message) {
    console.log(message);
};


4==globalData.roomStatus&&setTimeout(function(){
    try{
        var obj=eval("("+globalData.scoreboard+")");
        setTimeout(function(){socketModule.processLastScoreboard(obj)},0)
    }catch(e){
        console.log(e),setTimeout(function(){
            socketModule.processLastScoreboard("")
        },0)
    }
},50);

var isLoadAudioFile=!1;

var wxModule={
    config:function(){
        wx.config({
            debug:!1,
            appId:configData.appId,
            timestamp:configData.timestamp,
            nonceStr:configData.nonceStr,
            signature:configData.signature,
            jsApiList:["onMenuShareTimeline","onMenuShareAppMessage","hideMenuItems"]
        }),
        getShareContent(),
        wx.onMenuShareTimeline({
            title:globalData.shareTitle,
            desc:shareContent,
            link:globalData.roomUrl,
            imgUrl:globalData.imageUrl+"files/images/flower/share_icon.jpg",
            success:function(){},
            cancel:function(){}
        }),
        wx.onMenuShareAppMessage({
            title:globalData.shareTitle,
            desc:shareContent,
            link:globalData.roomUrl,
            imgUrl:globalData.imageUrl+"files/images/flower/share_icon.jpg",
            success:function(){},
            cancel:function(){}
        })
    }
};

var shareContent="";
function getShareContent(){
    // 1==appData.ruleInfo.chip_type?
    // shareContent+="筹码：2/4，4/8，8/16，10/20":
    // 2==appData.ruleInfo.chip_type?
    // shareContent+="筹码：2/4，5/10，10/20，20/40":
    // 3==appData.ruleInfo.chip_type&&
    // (shareContent+="筹码：10/20，20/40，50/100，100/200"),

    1==appData.ruleInfo.disable_pk&&(shareContent+=" 规则：闷牌，全场禁止比牌");
    2==appData.ruleInfo.ticket_count?shareContent+="  局数：12局x2张房卡":shareContent+="  局数：24局x4张房卡";
    0==appData.ruleInfo.look_cond>0?shareContent+=" 必闷轮数：无": shareContent+=" 必闷轮数："+appData.ruleInfo.look_cond;
}

wx.config({
    debug:!1,
    appId:configData.appId,
    timestamp:configData.timestamp,
    nonceStr:configData.nonceStr,
    signature:configData.signature,
    jsApiList:["onMenuShareTimeline","onMenuShareAppMessage","hideMenuItems"]
});

wx.ready(function(){
    audioModule.loadAllAudioFile(),
    wx.hideMenuItems({
        menuList:["menuItem:copyUrl","menuItem:share:qq","menuItem:share:weiboApp","menuItem:favorite","menuItem:share:facebook","menuItem:share:QZone","menuItem:refresh"]
    }),
    getShareContent(),
    wx.onMenuShareTimeline({
        title:globalData.shareTitle,
        desc:shareContent,
        link:globalData.roomUrl,
        imgUrl:globalData.imageUrl+"files/images/flower/share_icon.jpg",
        success:function(){},
        cancel:function(){}
    }),
    wx.onMenuShareAppMessage({
        title:globalData.shareTitle,
        desc:shareContent,
        link:globalData.roomUrl,
        imgUrl:globalData.imageUrl+"files/images/flower/share_icon.jpg",
        success:function(){},
        cancel:function(){}
    })
});
wx.error(function(e){});
